<template>
    <div>
        <!-- 可以随鼠标移动的图标 -->
        <div class="icon" @click="DialogController">
            <img src="@/assets/imgs/ai.png" class="ai-img" alt="点击唤醒图书助手"/>
        </div>
        <!-- 对话框 -->
        <div v-if="showDialogFlag" class="dialog" ref="chatContainer">
            <div class="left-chat">
                <div class="tip-left">历史消息</div>
                <el-menu :border="false" class="menu-history">
                    <el-menu-item v-for="item in historyList" :key="item.chatId" class="menu-item-chat" @click="getHistories(item)">
                        <div class="msgInfo-chat">{{ item.firstQuestion }}</div>
                    </el-menu-item>
                </el-menu>
                <div class="addIcon" @click="newChat" style="margin-top: 10px;">
                    <el-icon style="font-size: 30px;"><DocumentAdd /></el-icon>
                </div>
            </div>
            <div class="right-chat">
                <div class="tip-right">图书助手</div>
                <el-divider class="divider-right" />
                <el-card class="main-chat" shadow="false">
                    <div class="msg-ai">
                        <div class="name-chat2">图书助手</div>
                        <el-badge class="msg-text2">
                            <el-button class="contentOfChat2" round>请问我有什么能帮到你吗？</el-button>
                        </el-badge>
                    </div>
                    <div v-for="(item, index) in msgInfo" :key="index" class="msg-chat">
                        <div class="msg-user" v-if="item.order !== 0">
                            <div class="name-chat1">{{ this.username }}</div>
                            <el-badge class="msg-text1">
                                <el-button class="contentOfChat1" round>{{ item.question }}</el-button>
                            </el-badge>
                        </div>
                        <div class="msg-ai" v-if="item.order !== 0">
                            <div class="name-chat2">图书助手</div>
                            <el-badge class="msg-text2">
                                <el-button class="contentOfChat2" round>{{ item.answer }}</el-button>
                            </el-badge>
                        </div>
                    </div>
                </el-card>
                <div class="input-chat">
                    <div class="msg-input">
                        <textarea placeholder="请输入问题" v-model="askMessage.question" class="contentText"></textarea>
                        <el-button class="send" @click="sendQuestion" style="margin-left: 20px;margin-top: 5px;" type="primary" plain>发送</el-button>
                    </div>
                    
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios, { AxiosError } from 'axios'
export default {
    name: 'Chat',
    data() {
        return {
            showDialogFlag: false, // 控制对话框显示与隐藏的标志
            msgInfo:[],
            historyList:[],
            username:localStorage.getItem('username'),
            askMessage:{
                question : '',
                message  : '',
                username : localStorage.getItem('username'),
                chatId   :'' 
            },
            newMessage:{
                question : '',
                message  : 0,
                username : localStorage.getItem('username'),
                chatId   :'' 
            }
        };
    },
    methods: {
        DialogController() {
            this.showDialogFlag = !this.showDialogFlag;
        },
        newChat(){
            //清空msgInfo
            this.getNewChat()
        },
        //使用结构赋值进行异常处理
        promise_error_process(promise){
            return promise.then(data=>[null,data])
                            .catch(err=>[err,null])
		},
        async getHistoriesListByAjax(){
            const response = await axios({
                url				: `http://127.0.0.1:8080/api/gpt/listAnswer/${this.username}`,
                method			: 'GET',
                withCredentials : true
            })
            return response
        },
        async getHistoriesList(){
            const [err,result] = await this.promise_error_process(this.getHistoriesListByAjax())
            if(err)
                console.log(err)
            else{
                console.log(result)
                this.historyList = result.data.data
            }
        },
        async getHistoriesByAjax(item){
            const response = await axios({
                url				: 'http://127.0.0.1:8080/api/gpt/histories',
                method			: 'GET',
                withCredentials : true,
                params:{
                    username : this.username,
                    chatId   : item.chatId
                }
            })
            return response
        },
        async getHistories(item){
            this.askMessage.chatId = item.chatId
            const [err,result] = await this.promise_error_process(this.getHistoriesByAjax(item))
            if(err){
                console.log(err)
            }
            else{
                this.msgInfo = result.data.data
            }
        },
        async sendQuestionByAjax(){
            const response = await axios({
                url				: 'http://127.0.0.1:8080/api/gpt/ask',
                method			: 'POST',
                withCredentials : true,
                headers			: {
    				'Content-Type'	: 'application/json'
                },
                data            : this.askMessage
            })
            return response
        },
        async sendQuestion(){
            this.msgInfo.push({
                answer      : '小助正在头脑风暴，请您稍等片刻',
                order       : this.msgInfo.length,
                question    : this.askMessage.question
            })
            this.askMessage.message = 1
            const [err,result] = await this.promise_error_process(this.sendQuestionByAjax())
            if(err){
                console.log(err)
            }
            else{
                this.askMessage.question = ''
                console.log(result)
                this.msgInfo[this.msgInfo.length - 1].answer = result.data.data.response
                this.getHistoriesList()
            }
        },


        //获取新对话
        async getNewChatByAjax(){
            const response = await axios({
                url:                `http://127.0.0.1:8080/api/gpt/ask`,
                method:             'POST',
                withCredentials:    true,
                headers			: {
    				'Content-Type'	: 'application/json'
                },
                data            : this.newMessage
            })
            return response
        },
        async getNewChat(){
            this.msgInfo =[]
            const [err , result] = await this.promise_error_process(this.getNewChatByAjax())
            if(err){
                console.log("请求失败")
            }
            else{
                console.log(result)
                this.askMessage.chatId = result.data.data.chatId
                //产生新的历史记录
                this.getHistoriesList()
            }
        }
    },
    created(){
        this.getHistoriesList()
         let itemFirst = {
            username : this.username,
            chatId   : 0
        }
        this.getHistories(itemFirst)
    }
}
</script>

<style scoped>
.icon
.ai-img{
    width: 90px;
    height: 90px;
    margin-bottom: 5px;
}
.dialog {
  display: flex;
  position: fixed;
  right: 20px; /* 右侧位置 */
  top: 50px; /* 顶部位置 */
  height: 72%;
  width: 600px;
  background-color: white;
  padding: 10px;
  border: 1px solid black;
  border-radius: 10px;
}
.left-chat{
    width: 30%;
    display: block;
    height: 80%;
}
.tip-left{
    font-size: 15px;
    font-weight: 500;
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left: 10px;
    text-align: left;
}
.addIcon{
    display: flex;
    flex-direction: column;
    text-align: center;
    margin-left: 80px;
}
.addIcon:hover{
    cursor: pointer;
}
.menu-item-chat{
    text-align: left;
    border : none;
}
.divider-chat{
    margin-top: 20px;
    height: 90%;
}
.right-chat{
    width: 70%;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
}
.tip-right{
    text-align: left;
    vertical-align: bottom;
    font-size: 25px;
    position: absolute;
    height: 30px;
}
.divider-right{
    width: 100%;
    margin-top: 40px;
}
.msgInfo-chat{
    width: 100%;
}
.main-chat{
    height: 80%;
    overflow-y: auto;
}
.msg-chat{
    display: flex;
    flex-direction: column;
    text-align: left;
}
.name-chat1{
    font-size: 13px;
}
.msg-text1 {
    margin-top: 10px;
    margin-left: 30px;
}
.name-chat2{
    font-size: 13px;
}
.msg-text2 {
    margin-top: 10px;
    margin-right: 20px;
    
}
.msg-ai{
    text-align: left;
}
.msg-user{
    text-align: right;
}
.contentOfChat1{
    background-color: #409EFF;
    color: white;
    pointer-events: none;
    width: 100%;
    white-space: normal;
    height: auto;
    white-space: normal; 
    word-wrap: break-word;
    letter-spacing: 2px; /* 调整字间距 */
    line-height: 1.5; /* 调整行间距 */
    text-align: left; /* 文本左对齐 */
}
.contentOfChat2{
    background-color: #e1e2e2;
    pointer-events: none;
    width: 100%;
    white-space: normal;
    height: auto;
    white-space: normal; 
    word-wrap: break-word;
    letter-spacing: 2px; /* 调整字间距 */
    line-height: 1.5; /* 调整行间距 */
    text-align: left; /* 文本左对齐 */
}
.input-chat{
    height: 20px;
}
.msg-input{
    display: flex;
}
.contentText{
    width: 70%;
    margin-left: 20px;
    font-size: 15px;
    margin-top: 5px;
}
.menu-history{
    overflow-y: auto;
    height: 100%;
}
</style>